package com.heima.user.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.exception.CustomException;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.dto.LoginDTO;
import com.heima.model.user.pojo.ApUser;
import com.heima.model.user.vo.ApLoginVO;
import com.heima.user.mapper.ApUserMapper;
import com.heima.user.service.ApUserService;
import com.heima.utils.common.AppJwtUtil;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;
import org.apache.commons.lang3.StringUtils;

/**
 * @author: zhk
 * @since: 2025/6/12
 */
@Service
public class ApUserServiceImpl extends ServiceImpl<ApUserMapper, ApUser> implements ApUserService {
    @Override
    public ApLoginVO login(LoginDTO loginDTO) {
        String phone = loginDTO.getPhone();
        String password = loginDTO.getPassword();
        Long id = 0L;
        ApUser apUser = new ApUser();
        if (StringUtils.isNoneBlank(loginDTO.getPhone()) && StringUtils.isNoneBlank(loginDTO.getPassword())) {

            apUser = query().eq("phone", phone).one();
            if (apUser == null) {
                throw new CustomException(AppHttpCodeEnum.AP_USER_DATA_NOT_EXIST);
            }

            String apUserPassword = apUser.getPassword();
            String salt = apUser.getSalt();
            String passwordMd5 = DigestUtils.md5DigestAsHex((password + salt).getBytes());
            if (!passwordMd5.equals(apUserPassword)) {

                throw new CustomException(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR);
            }
            id = apUser.getId();

        }
        String token = AppJwtUtil.getToken(id);
        apUser.setId(id);
        apUser.setPassword("");
        apUser.setSalt("");
        ApLoginVO apLoginVO = ApLoginVO.builder()
                .apUser(apUser)
                .token(token)
                .build();

        return apLoginVO;
    }


}
